package logger

import (
	"fmt"
	"log"
	"os"
	"path/filepath"
	"time"
)

var (
	logFileErr   = new(*os.File)
	logFileVar   = new(*os.File)
	logFileDebug = new(*os.File)
)

// 20060102-${logType}.log
// todo: 盒子更新的时候记得干掉旧日志。
func writeLog(logType, m string) {
	globalSet.Lock()
	defer globalSet.Unlock()

	t := time.Now()
	formatT := t.Format("15:04:05")
	isOneFile := globalSet.isSingleLogFile

	fmt.Printf("%s\t%s\t%s\n", formatT, logType, m)

	logFile := new(*os.File)
	switch logType {
	case "var":
		logFile = logFileVar
	case "err":
		logFile = logFileErr
	case "debug":
		logFile = logFileDebug
	}

	// 构成log所需诸元
	var logFileName, msg, filePath string

	if isOneFile {
		filePath = globalSet.logPath
		msg = fmt.Sprintf("%s %s\t%s\n", formatT, logType, m)
	} else {
		logFileName = fmt.Sprintf("%s-%s.log", t.Format("20060102"), logType)
		msg = fmt.Sprintf("%s\t%s\n", formatT, m)
		filePath = filepath.Join(globalSet.logPath, logFileName)
	}

	if *logFile == nil {
		f, err := os.OpenFile(filePath, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0666)
		if globalSet.logPath == "" {
			log.Println("ops! logger cannot find output directory!")
			return
		}
		if err != nil {
			log.Println(err)
			return
		}

		*logFile = f
	}

	(*logFile).WriteString(msg)
}

func close() {
	logFiles := []**os.File{logFileErr, logFileVar, logFileDebug}
	for _, logFile := range logFiles {
		if *logFile != nil {
			(*logFile).Close()
			(*logFile) = nil
		}
	}
}
